package com.luoguijia.disk.spring.util;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;

@Component
public class MailUtil {

    @Value("${mail.host.name}")
    private String host;

    @Value("${mail.from.user}")
    private String fromUser;

    @Value("${mail.from.pwd}")
    private String fromPwd;

    /**
     * 发送邮件
     * @param to 收件人邮箱
     * @param subject 邮件主题
     * @param content 邮件内容
     * @return 是否发送成功
     */
    public boolean sendMail(String to, String subject, String content) {
        try {
            // 1. 创建Properties对象，设置邮件服务器信息
            Properties props = new Properties();
            props.setProperty("mail.transport.protocol", "smtp");
            props.setProperty("mail.smtp.host", host);
            props.setProperty("mail.smtp.auth", "true");
            props.setProperty("mail.smtp.port", "25");

            // 2. 创建Session对象
            Session session = Session.getDefaultInstance(props, new Authenticator() {
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(fromUser, fromPwd);
                }
            });

            // 3. 创建MimeMessage对象
            MimeMessage message = new MimeMessage(session);
            message.setFrom(new InternetAddress(fromUser));
            message.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
            message.setSubject(subject);
            message.setContent(content, "text/html;charset=UTF-8");

            // 4. 发送邮件
            Transport.send(message);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 发送验证码邮件
     * @param to 收件人邮箱
     * @param code 验证码
     * @return 是否发送成功
     */
    public boolean sendVerificationCode(String to, String code) {
        String subject = "密码重置验证码";
        String content = "<div style=\"font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto; padding: 20px; border: 1px solid #e0e0e0;\">"
                + "<h2 style=\"color: #333;\">密码重置验证码</h2>"
                + "<p>您正在尝试重置密码，您的验证码是：</p>"
                + "<div style=\"font-size: 24px; font-weight: bold; color: #007bff; margin: 20px 0;\">" + code + "</div>"
                + "<p>验证码有效期为5分钟，请在有效期内完成密码重置。</p>"
                + "<p>如果您没有请求重置密码，请忽略此邮件。</p>"
                + "</div>";
        return sendMail(to, subject, content);
    }
}